package com.sduept.nwld.dataserver.controller.ahp;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.CellEditEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.risk.model.ahp.RiskFactor;
import com.sduept.bigdata.risk.model.ahp.RiskFactorForModel;
import com.sduept.bigdata.risk.model.ahp.RiskFactorForModelItem;
import com.sduept.bigdata.risk.model.ahp.RiskFactorLevelItem;
import com.sduept.bigdata.risk.model.ahp.RiskFactorModel;
import com.sduept.bigdata.risk.model.ahp.RiskLevel;
import com.sduept.bigdata.risk.service.RiskFactorManager;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.entity.IdentifiedObject;
import com.sduept.nwld.dataserver.util.LibTreeNode;

@Named
@ViewScoped
public class RiskEvaluateModelController extends AbstractController {

	private static final long serialVersionUID = 4031184532916433117L;

	@Autowired
	private RiskFactorManager rfman;
	

	private IdentifiedObject current;
	private IdentifiedObject selected;
	
	private List<RiskFactorModel> models = new ArrayList<RiskFactorModel>();
	private List<RiskFactorForModel> rfmodels=new ArrayList<RiskFactorForModel>();
	private List<RiskFactorForModelItem> mitems = new ArrayList<RiskFactorForModelItem>();
	private RiskFactorForModelItem rfModelItem;
	private List<RiskFactorLevelItem> rlevels =new ArrayList<RiskFactorLevelItem>();
	private List<RiskFactor> riskFactors=new ArrayList<RiskFactor>();
	private List<RiskLevel> levels=new ArrayList<RiskLevel>();
	private TreeNode root;
	private TreeNode selectedNode;
	private boolean created=false;
	private String showInfo;
	@PostConstruct
	public void init(){
		try {
			root = new DefaultTreeNode();			
			models = rfman.findAllRFModels();
			if(models!=null && !models.isEmpty()){
				for(RiskFactorModel model : models){
					TreeNode rootd =  new LibTreeNode("model",model,root);
					rfmodels = rfman.findAllRFModelsByPid(model.getId());
					if (rfmodels!=null && rfmodels.size()>0){
						for(RiskFactorForModel rfmodel : rfmodels){
							new LibTreeNode("rfmodel",rfmodel,rootd);
						}
					}else{	
						if(model.getName().contains("一")){
							riskFactors=rfman.findRiskFactorByCondition("一");
						}else if(model.getName().contains("二")){
							riskFactors=rfman.findRiskFactorByCondition("二");
						}
						if(riskFactors!=null && riskFactors.size()>0){							
							for(RiskFactor rf : riskFactors){
								RiskFactorForModel rfmodel=new RiskFactorForModel();
								rfmodel.setName(rf.getName());
								rfmodel.setRiskFactorDesc(rf.getRiskFactorDesc());
								rfmodel.setBasicWeight(1);
								rfmodel.setPid(model.getId());
								rfman.createRiskFactorForModel(rfmodel);
							}
							for(RiskFactor rf : riskFactors){
								new LibTreeNode("rfmodel",rf,rootd);
							}
						}
					}
					rootd.setExpanded(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void preCreate(String type){
		created=true;
		if("mitem".equals(type)){
			current = new RiskFactorForModelItem();
			((RiskFactorForModelItem)current).setFactorName(((RiskFactorForModel)selectedNode.getData()).getName());;
		} else if("model".equals(type)){
			current = new RiskFactorModel();
		} else if("level".equals(type)){
			rlevels.clear();
			if(rfModelItem!=null){
				rlevels=rfman.findAllRFLevelItemsByPid(rfModelItem.getId());
				if(selectedNode.getType().equals("model")){
					showInfo=((RiskFactorModel)selectedNode.getData()).getName();
				}else if(selectedNode.getType().equals("rfmodel")){
					showInfo=((RiskFactorModel)selectedNode.getParent().getData()).getName();
				}
				showInfo=showInfo+"-"
						+rfModelItem.getName()+"【"
						+rfModelItem.getFactorMinValue()+"-"+
						rfModelItem.getFactorMaxValue()+"】";
				if(rlevels==null || rlevels.isEmpty()){
					levels=rfman.findAllRiskLevelOrderById();
					if(levels!=null && !levels.isEmpty()){
						for(RiskLevel level:levels){
							RiskFactorLevelItem rlevel=new RiskFactorLevelItem();
							rlevel.setLevelName(level.getName());
							rlevel.setLevelWeight(1.0d);
							rlevel.setPid(rfModelItem.getId());
							rlevel=rfman.createRiskFactorLevelItem(rlevel);
							rlevels.add(rlevel);							
						}
					}
				}				
			}
			rfModelItem=null;
		}
	}
	
	public void preUpdate(String type){
		created=false;
		if(type.equals("model")){
			current = (RiskFactorModel)selectedNode.getData();
		} else if(type.equals("mitem")){
			if(rfModelItem!=null)
				current = rfModelItem;
		} 
	}
	
	public void create(){
		try {
			if(selectedNode != null && current != null){
				if(!created){
					 if(current instanceof RiskFactorModel){
						rfman.updateRiskFactorModel((RiskFactorModel) current);
					} else if(current instanceof RiskFactorForModelItem){
						mitems.remove((RiskFactorForModelItem) current);
						rfman.updateRiskFactorModelItem((RiskFactorForModelItem) current);
						mitems.add((RiskFactorForModelItem) current);
					}
				} else {
					if(current instanceof RiskFactorForModelItem){						
						((RiskFactorForModelItem) current).setPid(((RiskFactorModel)selectedNode.getParent().getData()).getId());	
						((RiskFactorForModelItem) current).setRid(((RiskFactorForModel)selectedNode.getData()).getId());	
						((RiskFactorForModelItem) current).setName(((RiskFactorForModelItem)current).getFactorName());						
						rfman.createRiskFactorModelItem((RiskFactorForModelItem)current);
						mitems.add((RiskFactorForModelItem)current);
					} else if(current instanceof RiskFactorModel){
						RiskFactorModel model = rfman.createRiskFactorModel((RiskFactorModel) current);
						models.add(model);
						TreeNode rootd =new DefaultTreeNode("model", model, root);
						if(riskFactors!=null && riskFactors.size()>0){							
							for(RiskFactor rf : riskFactors){
								RiskFactorForModel rfmodel=new RiskFactorForModel();
								rfmodel.setName(rf.getName());
								rfmodel.setRiskFactorDesc(rf.getRiskFactorDesc());
								rfmodel.setBasicWeight(1);
								rfmodel.setPid(model.getId());
								rfman.createRiskFactorForModel(rfmodel);
							}
							for(RiskFactor rf : riskFactors){
								new LibTreeNode("rfmodel",rf,rootd);
							}
						}
					}
				}
				addSuccessMessage("保存成功！");
			} else {
				if(current != null && current instanceof RiskFactorModel){
					RiskFactorModel model = rfman.createRiskFactorModel((RiskFactorModel) current);
					models.add(model);
					new DefaultTreeNode("model", model, root);
				}
			}
		} catch (Exception e) {
			addErrorMessage("保存失败！");
			e.printStackTrace();
		}finally{
			current = null;
			created=!created;
		}
	}
	public void delete(){
		if(selectedNode != null){
			try {
				if(selectedNode.getType().equals("model")){
					RiskFactorModel model= (RiskFactorModel) selectedNode.getData();					
					if(selectedNode.getChildren().size()>0){
						for(TreeNode tnChild:selectedNode.getChildren()){	
							if(tnChild.getType().equals("rfmodel")){								
								RiskFactorForModel rfmodel = (RiskFactorForModel)tnChild.getData();
								rfman.deleteRiskFactorModelItemByPid(rfmodel.getId());
								rfman.deleteRiskFactorForModel(rfmodel.getId());
								mitems.remove(rfmodel);
							}
						}
					}
					rfman.deleteRiskFactorModel(model.getId());
					selectedNode.getParent().getChildren().remove(selectedNode);					
				} else if(selectedNode.getType().equals("rfmodel")){
					RiskFactorForModel rfmodel = (RiskFactorForModel) selectedNode.getData();
					rfman.deleteRiskFactorModelItemByPid(rfmodel.getId());
					rfman.deleteRiskFactorModel(rfmodel.getId());
					selectedNode.getParent().getChildren().remove(selectedNode);
					mitems.clear();
				} 
				addSuccessMessage("删除成功");
				selectedNode=null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void onNodeExpand(NodeExpandEvent event){
		selectedNode = event.getTreeNode();
		expandNode(selectedNode);
	}
	
	public void onNodeSelect(NodeSelectEvent event){
		if(rfModelItem!=null)rfModelItem=null;
		selectedNode = event.getTreeNode();
		try {
			if("model".equals(selectedNode.getType())){
				selected = (RiskFactorModel) selectedNode.getData();
				mitems = rfman.findAllRFMItemsByPid(((RiskFactorModel)selected).getId());				
			}else if("rfmodel".equals(selectedNode.getType())){
				selected = (RiskFactorForModel)selectedNode.getData();
				mitems = rfman.findAllRFMItemsByRid(((RiskFactorForModel)selected).getId());		
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void expandNode(TreeNode node){
		if(node.getType().equals("model")){
			RiskFactorModel model = (RiskFactorModel) node.getData();
			try {
				mitems= rfman.findAllRFMItemsByPid(model.getId());
				if (mitems!=null && mitems.size()>0){
					for(RiskFactorForModelItem mitem : mitems){
						new LibTreeNode("mitem",mitem,node);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} 
	}	
	
	public void onCellEdit(CellEditEvent event) {
		for(RiskFactorLevelItem level:rlevels){			
			if(level.getId().equals(rlevels.get(event.getRowIndex()).getId())){
				Object oldValue = event.getOldValue();
		        Object newValue = event.getNewValue();	
		        if(newValue != null && !newValue.equals(oldValue)) {
		        	level.setLevelWeight(Double.valueOf(newValue.toString()));
		            try {
						rfman.updateRiskFactorLevelItem(level);
						break;
					} catch (Exception e) {
						e.printStackTrace();
					}
		         }
			}					
		}    
    }
	
	
	public TreeNode getRoot() {
		return root;
	}
	
	public void setRoot(TreeNode root) {
		this.root = root;
	}
	
	public TreeNode getSelectedNode() {
		return selectedNode;
	}
	
	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = selectedNode;
	}
	
	public boolean isCreated() {
		return created;
	}
	
	public void setCreated(boolean created) {
		this.created = created;
	}
		
	public IdentifiedObject getCurrent() {
		return current;
	}
	
	public void setCurrent(IdentifiedObject current) {
		this.current = current;
	}
	
	public IdentifiedObject getSelected() {
		return selected;
	}
	
	public void setSelected(IdentifiedObject selected) {
		this.selected = selected;
	}
	
	public List<RiskFactorModel> getModels() {
		return models;
	}
	
	public void setModels(List<RiskFactorModel> models) {
		this.models = models;
	}
	public List<RiskFactorForModelItem> getMitems() {
		return mitems;
	}
	public void setMitems(List<RiskFactorForModelItem> mitems) {
		this.mitems = mitems;
	}

	public List<RiskFactorLevelItem> getRlevels() {
		return rlevels;
	}

	public void setRlevels(List<RiskFactorLevelItem> rlevels) {
		this.rlevels = rlevels;
	}

	public List<RiskLevel> getLevels() {
		return levels;
	}

	public void setLevels(List<RiskLevel> levels) {
		this.levels = levels;
	}

	public List<RiskFactor> getRiskFactors() {
		return riskFactors;
	}

	public void setRiskFactors(List<RiskFactor> riskFactors) {
		this.riskFactors = riskFactors;
	}

	public List<RiskFactorForModel> getRfmodels() {
		return rfmodels;
	}

	public void setRfmodels(List<RiskFactorForModel> rfmodels) {
		this.rfmodels = rfmodels;
	}

	public RiskFactorForModelItem getRfModelItem() {
		return rfModelItem;
	}

	public void setRfModelItem(RiskFactorForModelItem rfModelItem) {
		this.rfModelItem = rfModelItem;
	}

	public String getShowInfo() {
		return showInfo;
	}

	public void setShowInfo(String showInfo) {
		this.showInfo = showInfo;
	}

	
}
